
package com.itheima.controller.backend.security;

import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserService userService;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用用户服务获取用户信息
        User user = userService.findByUsername(username);
        Set<Permission> permissions = new HashSet<>();
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        log.info("用户信息：{}", user);
        // 查询用户的角色
        List<Role> roles = userService.loadRolesByUserId(user.getId());

        //查询当前用户权限
        for (Role role : roles) {
            permissions = userService.getPermissions(role.getId());
            role.setPermissions(permissions);
            LinkedHashSet<Menu> menus = userService.getMenus(role.getId());
            role.setMenus(menus);
        }

        //封装当前用户的角色和权限
        List<GrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getKeyword()))
                .collect(Collectors.toList());
        authorities.addAll(permissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getKeyword()))
                .collect(Collectors.toList()));
        log.info("authorities：{}", authorities);
        //返回带用户名，密码，权限列表的user对象User(username,user.getPassword(),list)
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .build();
    }
}


